import numpy as np
import sys;
import yuque;
import json;
import re;
import numpy as np;
import requests as req
from PIL import Image, ImageDraw, ImageFont
from io import BytesIO;
import toke;
import time;
import mysql.connector;
class img():

    def getDb(self,quer):

        mydb = mysql.connector.connect(
          host="localhost",       # 数据库主机地址
          user="root",    # 数据库用户名
          passwd="root",   # 数据库密码
          database="weizandata"
        )

        mycursor = mydb.cursor()
        mycursor.execute(quer)
        myresult = mycursor.fetchall()  

        return myresult

    def gen_img(self,size=None,color=None):

        if size is None:
            size = 400
        if color is None:
            color = (255, 255, 255)
            #生成大小为400x400RGBA是四通道图像，RGB表示R，G，B三通道，A表示Alpha的色彩空間
        image = Image.new(mode='RGBA', size=size, color= color)
        # ImageDraw.Draw 简单平面绘图
        draw_table = ImageDraw.Draw(im=image)

        return image

    def pic_open(self,filepath):
        #图片打开与显示
        image = Image.open(filepath)
        return image
            
    def get_size(self,image):
        #获取图像的宽和高
        width, height = image.size
        return width,heitht

    def pic_text_nickname(self,text):

        fontSize=10

        setFont = ImageFont.truetype('C:/windows/fonts/simhei.ttf', fontSize) #设置字体

        lt_box_width=len(text)*fontSize+10  #聊天记录框宽度

        lt_box_height=10 #聊天记录框高度

        lt_box=self.gen_img((lt_box_width,lt_box_height),(255,255,255)) #新建聊天记录框

        draw=ImageDraw.Draw(lt_box)

        draw.text((0,0),text,font=setFont,fill='rgb(50,50,50)',direction=None)

        return lt_box


    def pic_text(self,fontSize,text,backgroundColor,fontFillColor,direction=None):

        #fontSize=15 #字体大小

        line_font_size=50

        setFont = ImageFont.truetype('C:/windows/fonts/simhei.ttf', fontSize) #设置字体

        font_size=len(text) #本条记录的字数

        if(font_size<=line_font_size):

            
            lt_box_col_size=font_size

        else:

            lt_box_col_size=line_font_size #一行20个字


        lt_box_width=lt_box_col_size*fontSize+10  #聊天记录框宽度

        lt_box_height=round(font_size*(fontSize)/lt_box_width*fontSize)+20 #聊天记录框高度

        lt_box=self.gen_img((lt_box_width,lt_box_height),backgroundColor) #新建聊天记录框 (3,155,229)

        text_sem=0

        line_height=5

        for txt in text:

            if( text_sem <= lt_box_col_size):

                draw=ImageDraw.Draw(lt_box)

                if(text_sem==0):

                    text_semi=5

                else:

                   text_semi=text_sem*fontSize+5

            draw.text((text_semi,line_height),txt,font=setFont,fill='rgb'+fontFillColor,direction=None) #(255,255,255)

            text_sem=text_sem+1

            if(text_sem ==lt_box_col_size):

                line_height=line_height+fontSize

                text_sem=0

        return lt_box

        #print(filepath,size,text,setFont,fillColor)
        #打开图片
       # image=pic_open(filepath)
        #新建绘图对象
        #draw = ImageDraw.Draw(image)
        #显示图片
        #image.show()
        #draw.text(size,text,font=setFont,fill=fillColor,direction=None)
        #image.show()
        #保存
        # pic_save(image,filename)

        #image.paste(lt_box,(40,40),mask=None)



    def pic_save(self,image,filename):
        #保存
        image.save(filename)   

    def mergeReport(self,files):

        baseimg=Image.open(files[0])
        sz = baseimg.size
        basemat=np.atleast_2d(baseimg)
        for file in files[1:]:
            im=Image.open(file)
        #resize to same width
            sz2 = im.size
            if sz2!=sz:
                im=im.resize((sz[0],round(sz2[0] / sz[0] * sz2[1])),Image.ANTIALIAS)
            mat=np.atleast_2d(im)
            basemat=np.append(basemat,mat,axis=0)
        report_img=Image.fromarray(basemat)
        report_img.save('merge.png')

    def mergeImg(self,files):

        baseimg=files[0]
        sz = baseimg.size
        basemat=np.atleast_2d(baseimg)
        for file in files[1:]:
            im=file
        #resize to same width
            sz2 = im.size
            if sz2!=sz:
                im=im.resize((sz[0],round(sz2[0] / sz[0] * sz2[1])),Image.ANTIALIAS)
            mat=np.atleast_2d(im)
            basemat=np.append(basemat,mat,axis=0)
        report_img=Image.fromarray(basemat)

        return report_img

    def createImgLt(self,openId,fileName):


        img=self;

        yq=yuque.yueque();

        tk=toke.toke();

        chatlog=json.loads(yq.userLianTianJiLu(openId))['result']['data']; #聊天记录

        chatlog=sorted(chatlog,key=lambda i:i['microtime'])#排序

        userInfo=tk.getWxUserInfo(openId)

        bgckgroundImg=769

        image=img.gen_img((bgckgroundImg,100),(255,255,255))

        worke=img.pic_open('a.jpg');

        img_src=userInfo['avatar']

        response = req.get(img_src)

        head = Image.open(BytesIO(response.content)) #头像

        user=head.resize((30,30)); #重置头像大小

        nickname_img=img.pic_text_nickname(userInfo['nickname']) #微信昵称图片

        margin_top=60

        for i in range(0,len(chatlog)):

            if(chatlog[i]['from']=='worker'):

                txt=chatlog[i]['text'] #文本

                lt_box=img.pic_text(10,txt,(3,155,255),'(255,255,255)') #写入聊天文本

                lt_box_size=lt_box.size #获取聊天框大小

                microtime=chatlog[i]['microtime'] #转换时间戳

                micrDate=img.pic_text_nickname(img.zhtime(microtime,"%Y-%m-%d %H:%M:%S")) 

                image=img.mergeImg([image,img.gen_img((bgckgroundImg,lt_box_size[1]+20),(255,255,255))]) #增加背景图片高度

                image.paste(micrDate,(round(bgckgroundImg-155),margin_top-10),mask=None) #粘贴沟通时间

                image.paste(worke,(round(bgckgroundImg-50),margin_top),mask=None) #粘贴头像

                image.paste(lt_box,(round(bgckgroundImg)-lt_box_size[0]-60,margin_top),mask=None) #粘贴聊天框

                margin_top=margin_top+lt_box_size[1]+20 #增加下边距离

            elif(chatlog[i]['from']=='user'):

                txt=chatlog[i]['text']

                srcObj=re.search(r'http://mmbiz.qpic.cn/mmbiz_jpg/[a-zA-Z0-9/]+',txt,re.M)

                if srcObj:

                    src=srcObj.group(0)

                    lt_box=img.srcImg(src,5)

                    print(lt_box.size)
                
                else:

                    txt=re.sub(r'<a.*>','[链接]',txt)

                    lt_box=img.pic_text(10,txt,(229,234,236),'(0,0,0)')

                lt_box_size=lt_box.size

                microtime=chatlog[i]['microtime'] #转换时间戳

                micrDate=img.pic_text_nickname(img.zhtime(microtime,"%Y-%m-%d %H:%M:%S")) 

                image=img.mergeImg([image,img.gen_img((bgckgroundImg,lt_box_size[1]+20),(255,255,255))])

                image.paste(nickname_img,(10,margin_top-10),mask=None)  #粘贴头像

                image.paste(micrDate,(50,margin_top-10),mask=None) #粘贴沟通时间

                image.paste(user,(10,margin_top),mask=None) #粘贴微信昵称

                image.paste(lt_box,(50,margin_top),mask=None)#粘贴聊天框

                margin_top=margin_top+lt_box_size[1]+20

        # lt_box=img.pic_text(15,txt)

        # image.paste(lt_box,(10,40),mask=None)
        #image.show()

        image.save('C:/liaotian/'+fileName+'.png')

    def zhtime(self,timeStamp,format):

            timeStamp=round(timeStamp/1000)

            timeArray = time.localtime(timeStamp)
            
            otherStyleTime = time.strftime(format, timeArray)

            return otherStyleTime

    def srcImg(self,img_src,sela):

        response = req.get(img_src)

        head = Image.open(BytesIO(response.content)) #头像

        head_size=head.size

        head=head.resize((round(head_size[0]/sela),round(head_size[1]/sela)))

        return head
       
# if __name__=="__main__":

#     # size=None
#     # #gen_img()
        
#     # #** ImageFont模块**
#     # #选择文字字体和大小
#     # setFont = ImageFont.truetype('C:/windows/fonts/aldhabi.ttf', 20)
#     # #设置文字颜色
#     # fillColor = "#0000ff"   #蓝色
#     # text="兔子等着瞧"
#     # size=(40,40)
#     # filepath="C:/python/img/red.png"
#     # filename="C:/python/img/redsave.png"

#     # #打开图片
#     # image=pic_open(filepath)
#     # #添加文字
#     # pic_text(filepath,size,text,setFont,fillColor,filename,direction=None)